<template>
  <el-dialog :visible.sync="dialogVisible" :title="curId ? '编辑服务器' : '新增服务器'" width="750px" :before-close="close">
    <el-form ref="ruleForm" inline label-position="left" :model="ruleForm" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-card shadow="never">
        <el-form-item label="云平台" prop="cloud">
          <el-select v-model="ruleForm.cloud" clearable placeholder="云平台" @change="setPrivateInstanceId">
            <el-option
              v-for="item in serverCloud"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="地域" prop="zone">
          <el-select v-model="ruleForm.zone" clearable placeholder="地域">
            <el-option
              v-for="item in serverZone"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务器名称" prop="name">
          <el-input v-model="ruleForm.name" clearable autocomplete="off" @input="getServerName" />
        </el-form-item>
        <el-form-item label="实例ID" prop="instance_id">
          <el-input v-model="ruleForm.instance_id" clearable autocomplete="off" :disabled="ruleForm.cloud === 'private'" />
        </el-form-item>
        <el-form-item label="内存" prop="memory">
          <el-input v-model="ruleForm.memory" clearable autocomplete="off" />
        </el-form-item>
        <el-form-item label="CPU" prop="cpu">
          <el-input v-model="ruleForm.cpu" clearable autocomplete="off" />
        </el-form-item>
        <el-form-item label="ipv4" prop="ipv4">
          <el-input v-model="ruleForm.ipv4" clearable autocomplete="off" />
        </el-form-item>
        <el-form-item label="ipv6" prop="ipv6">
          <el-input v-model="ruleForm.ipv6" clearable autocomplete="off" />
        </el-form-item>
        <el-form-item label="公网ip" prop="pub_ip">
          <el-input v-model="ruleForm.pub_ip" clearable autocomplete="off" />
        </el-form-item>
        <el-form-item label="类型" prop="os">
          <el-select v-model="ruleForm.os" clearable placeholder="操作系统类型">
            <el-option
              v-for="item in serverTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="运行状态" prop="status">
          <el-select v-model="ruleForm.status" clearable placeholder="机器运行状态">
            <el-option
              v-for="item in serverStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="资产标识" prop="belong_flag">
          <el-input v-model="ruleForm.belong_flag" clearable autocomplete="off" />
        </el-form-item>
      </el-card>

      <el-card shadow="never">
        <el-form-item label="创建时间" prop="create_date">
          <el-date-picker
            v-model="ruleForm.create_date"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="过期时间" prop="expired_date">
          <el-date-picker
            v-model="ruleForm.expired_date"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
      </el-card>
      <el-card>
        <div>
          <el-tag type="success">Tags</el-tag>
        </div>
        <el-form-item label="环境" prop="tags_env">
          <el-select v-model="ruleForm.tags_env" clearable placeholder="Tags 环境">
            <el-option
              v-for="item in tags_env"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="tags_owner">
          <el-select v-model="ruleForm.tags_owner" multiple clearable placeholder="Tags 负责人">
            <el-option
              v-for="item in tags_owner"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="应用" prop="tags_app">
          <el-input v-model="ruleForm.tags_app" clearable autocomplete="off" />
        </el-form-item>
        <div>
          <el-button type="primary" icon="el-icon-plus" size="small" circle @click="tagAddOne" />
        </div>

        <div v-for="(item, index) in ruleForm.tags_add" :key="index">

          <el-form-item label="Tag key">
            <el-input v-model="item.label" clearable autocomplete="off" />
          </el-form-item>

          <el-form-item label="Tag value">
            <el-input v-model="item.value" clearable autocomplete="off" />
          </el-form-item>

          <el-form-item>
            <el-button type="danger" icon="el-icon-delete" circle @click="tagDeleteOne(item)" />
          </el-form-item>
        </div>
      </el-card>
      <el-card>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-card>
    </el-form>

  </el-dialog>
</template>

<script>
import { createServer, updateServer, getServer } from '@/api/cmdb/server'

export default {
  name: 'CuForm',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    curId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      ruleForm: {
        tags_add: []
      },
      ipv4_options: [],
      rolesData: [],
      tags_env: [
        {
          value: 'dev',
          label: 'dev'
        },
        {
          value: 'test',
          label: 'test'
        },
        {
          value: 'sit',
          label: 'sit'
        },
        {
          value: 'uat',
          label: 'uat'
        },
        {
          value: 'prod',
          label: 'prod'
        }
      ],
      tags_owner: [

        {
          value: '小王',
          label: '小王'
        },

        {
          value: '小张',
          label: '小张'
        },

        {
          value: '小李',
          label: '小李'
        }

      ],
      serverZone: [
        {
          value: 'beijing',
          label: '北京'
        },
        {
          value: 'shanghai',
          label: '上海'
        }

      ],

      serverValues: [
        {
          label: 'value1',
          value: 'value1'
        },
        {
          value: 'value2',
          label: 'value2'
        }

      ],
      serverCloud: [
        // {
        //   value: 'tencent',
        //   label: '腾讯云'
        // },
        // {
        //   value: 'ali',
        //   label: '阿里云'
        // },
        {
          value: 'private',
          label: '私有云'
        }

      ],
      serverTypeOptions: [
        {
          value: 'Windows Server',
          label: 'Windows Server'
        },
        {
          value: 'Linux Centos7',
          label: 'Linux Centos7'
        }
      ],
      serverStatus: [
        {
          value: 'Running',
          label: '运行中'
        },
        {
          value: 'Stopped',
          label: '关机'
        }
      ],
      rules: {
        name: [{ required: true, trigger: 'blur', message: '必填参数' }],
        memory: [{ required: true, trigger: 'blur', message: '必填参数' }],
        cpu: [{ required: true, trigger: 'blur', message: '必填参数' }],
        ipv4: [{ required: true, trigger: 'blur', message: '必填参数' }],
        os: [{ required: true, trigger: 'blur', message: '必填参数' }],
        status: [{ required: true, trigger: 'blur', message: '必填参数' }],
        belong_flag: [{ required: true, trigger: 'blur', message: '必填参数' }],
        create_date: [{ required: true, trigger: 'blur', message: '必填参数' }],
        tags_env: [{ required: true, trigger: 'blur', message: '必填参数' }],
        tags_owner: [{ required: true, trigger: 'blur', message: '必填参数' }],
        tags_app: [{ required: true, trigger: 'blur', message: '必填参数' }]

      }
    }
  },
  watch: {
    dialogVisible(v) {
      console.log(this.ruleForm.tags_add);
      if (v) {
        // console.log('dialogVisible :watch',v);
        if (this.curId) {
          console.log(this.curId)
          getServer(this.curId).then(res => {
            this.ruleForm = res.data
            const tags = res.data.tags
            const tags_add = []
            JSON.parse(tags).forEach(tag => {
              if (tag.hasOwnProperty('env')) {
                // this.ruleForm.tags_env = tag["env"]
                this.ruleForm = Object.assign({}, this.ruleForm, { tags_env: tag['env'] })
                console.log(tag['env'])
              } else if (tag.hasOwnProperty('app')) {
                // this.ruleForm.tags_app = tag["app"]
                this.ruleForm = Object.assign({}, this.ruleForm, { tags_app: tag['app'] })
                console.log(tag['app'])
              } else if (tag.hasOwnProperty('owner')) {
                const owner = tag['owner'].split('/')
                // this.ruleForm.tags_owner = owner
                this.ruleForm = Object.assign({}, this.ruleForm, { tags_owner: owner })
                console.log(owner)
              } else {
                Object.keys(tag).forEach(key => {
                  tags_add.push({ 'label': key, 'value': tag[key] })
                  console.log(tags_add)
                })
                this.ruleForm = Object.assign({}, this.ruleForm, { tags_add: tags_add })
              }
            })
            console.log('get server ', this.ruleForm)
          })
        }
      }
    }
  },
  created() {
  },
  methods: {
    tagDeleteOne(item) {
      for (let i = 0; i < this.ruleForm.tags_add.length; i++) {
        if (this.ruleForm.tags_add[i].label === item.label && this.ruleForm.tags_add[i].value === item.value) {
          this.ruleForm.tags_add.splice(i, 1)
        }
      }
    },
    tagAddOne() {
      // console.log(this.ruleForm)
      if (!this.ruleForm.tags_add) {
        this.$set(this.ruleForm, 'tags_add', [])
        // Object.assign(this.ruleForm, { tags_add: [] })
        // this.ruleForm = Object.assign({}, this.ruleForm, { tags_add: [] })
      }
      this.ruleForm.tags_add.push({
        label: '',
        value: ''
      })
    },
    search() {
      this.close()
      this.$emit('search')
    },
    close() {
      console.log('close function')
      this.$refs.ruleForm.resetFields()
      this.ruleForm.tags_add=[]
      this.$emit('close')
    },
    getServerName(val) {
      if (this.ruleForm.cloud === 'private') {
        this.ruleForm.instance_id = val
      }
    },
    setPrivateInstanceId(val) {
      if (val === 'private') {
        this.ruleForm.instance_id = this.ruleForm.name
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.curId) {
            let owner_str = ''
            this.ruleForm.tags_owner.forEach(owner => {
              owner_str = owner_str + owner + '/'
            })
            console.log('update user', this.ruleForm)
            const tags = [{ 'env': this.ruleForm.tags_env }, { 'owner': owner_str.slice(0, length - 1) }, { 'app': this.ruleForm.tags_app }]

            if (this.ruleForm.tags_add) {
              this.ruleForm.tags_add.forEach(value => {
                tags.push({ [value['label']]: value['value'] })
              })
            }
            this.ruleForm.tags = JSON.stringify(tags)

            updateServer(this.curId, this.ruleForm).then(res => {
              if (res.code == 200){
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.search()
              }
            })
          } else {
            let owner_str = ''
            this.ruleForm.tags_owner.forEach(function(owner) {
              owner_str = owner_str + owner + '/'
            })
            const tags = [{ 'env': this.ruleForm.tags_env }, { 'owner': owner_str.slice(0, length - 1) }, { 'app': this.ruleForm.tags_app }]
            this.ruleForm.tags_add.forEach(function(value) {
              tags.push({ [value['label']]: value['value'] })
            })
            this.ruleForm.tags = JSON.stringify(tags)
            console.log(this.ruleForm)
            createServer(this.ruleForm).then(res => {
              if (res.code == 200){
                this.$message({
                  message: '新增成功',
                  type: 'success'
                })
                this.search()
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
